package com.wonders.common.web.wrapper;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang3.StringEscapeUtils;

/**
 * 自定义请求包装对象
 * 
 * @author WuBin
 * 
 */
public class ParameterRequestWrapper extends HttpServletRequestWrapper {

	private HttpServletRequest orgRequest = null;

	public ParameterRequestWrapper(HttpServletRequest request) {
		super(request);
		orgRequest = request;
	}

	@Override
	public String getParameter(String name) {
		String value = super.getParameter(name);
		if (value != null) {
			value = strEncode(value);
		}
		return value;
	}

	@Override
	public String[] getParameterValues(String name) {
		String[] value = super.getParameterValues(name);
		String[] newArray = null;
		if (value != null) {
			newArray = new String[value.length];
			for (int i = 0; i < value.length; i++) {
				newArray[i] = strEncode(value[i]);
			}
		}
		return newArray;
	}

	@Override
	public Map<String, String[]> getParameterMap() {
		Map<String, String[]> value = super.getParameterMap();
		Map<String, String[]> newMap = null;
		if (value != null) {
			newMap = new HashMap<String, String[]>();
			for (Entry<String, String[]> entry : value.entrySet()) {
				String[] v = entry.getValue();
				if (v != null) {
					String[] newArray = new String[v.length];
					for (int i = 0; i < v.length; i++) {
						newArray[i] = strEncode(v[i]);
					}
					newMap.put(entry.getKey(), newArray);
				}
			}
		}
		return newMap;
	}

	@Override
	public String getHeader(String name) {
		String value = super.getHeader(name);
		if (value != null) {
			value = strEncode(value);
		}
		return value;
	}

	private String strEncode(String s) {
		if (s == null || s.isEmpty()) {
			return s;
		}
		return StringEscapeUtils.escapeHtml4(s);
	}

	public HttpServletRequest getOrgRequest() {
		return orgRequest;
	}

	public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
		if (req instanceof ParameterRequestWrapper) {
			return ((ParameterRequestWrapper) req).getOrgRequest();
		}
		return req;
	}

}
